package com.atcumt.Jike.map;

import java.util.ArrayList;
import java.util.List;

// 原地hash
public class Hash01 {
    
    /* 
     * 缺失的第一个正数
     * 数值为 i 的数映射到下标为 i - 1 的位置
     * 重点：nums[nums[i] - 1] != nums[i]
     */
    public int firstMissingPositive(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < nums.length; i++) {
            // 构建hash表
            while(nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
                swap(nums, nums[i] - 1, i);
            }
        }
        // [1, -1, 3, 4]
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i + 1) {
                return i  + 1;
            }
        }
        return n + 1;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    /* 
     * 数组中重复的数据
     */
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            while (nums[nums[i] - 1] != nums[i]) {
                swap(nums, nums[i] - 1, i);
            }
        }
        for (int i = 0; i < n; i++) {
            if (nums[i] - 1 != i) {
                res.add(nums[i]);
            }
        }
        return res;
    }
    
    public static void main(String[] args) {
        System.out.println(foo(6));
    }

    private static int foo(int n) {
        if (n < 2) {
            return n;
        }
        return foo(n - 1) + foo(n - 2);
    }
}
